﻿using Dapper;
using Finance.API.Read.Application.Command.ReceivablesManagementCommand;
using Finance.Domain;
using Finance.Dtos;
using Finance.ErrorCode;
using Finance.Infrastructrue.Implement;
using MediatR;
using System.Text;

namespace Finance.API.Read.Application.Hander.ReceivablesManagementHander
{
    public class ShowReceivablesManagementHander:IRequestHandler<ShowReceivablesManagementCommand,APIPaging<ReceivablesManagementDto>>
    {
        DatabaseContext db;
        ILogger<ShowReceivablesManagementHander> logger;

        public ShowReceivablesManagementHander(DatabaseContext db, ILogger<ShowReceivablesManagementHander> logger)
        {
            this.db = db;
            this.logger = logger;
        }

        public async Task<APIPaging<ReceivablesManagementDto>> Handle(ShowReceivablesManagementCommand request, CancellationToken cancellationToken)
        {
            APIPaging <ReceivablesManagementDto> result=new APIPaging<ReceivablesManagementDto> ();
            StringBuilder sb=new StringBuilder ();
            StringBuilder page=new StringBuilder ();
            try
            {
                sb.Append(@"SELECT
                               a.ReceivablesManagementId,
                               a.FlowingWaterNumber,
                               a.ReceivablesManagementName,
                               a.ReceivablesManagementType,
                               a.Payer,
                               a.AmountReceivable,
                               a.PaidInAmount,
                               a.RemainingAmount,
                               a.State,
                               a.LastPaymentDate,
                               a.Recipients,
                               a.NumberOfPayments,
                               a.Remark,
                               a.PaymentInstitutions,
                               a.CreatTime,
                               a.CreatName,
                               b.CategoryName
                            FROM receivablesmanagement AS a
                            JOIN financialCategory AS b ON a.ReceivablesManagementType=b.FinancialCategoryId
                            WHERE a.IsDel=FALSE");
                page.Append(@"SELECT
                              COUNT(a.ReceivablesManagementId)
                            FROM receivablesmanagement AS a
                            JOIN financialCategory AS b ON a.ReceivablesManagementType=b.FinancialCategoryId
                            WHERE a.IsDel=FALSE");

                if (!string.IsNullOrEmpty(request.FlowingWaterNumber))
                {
                    sb.Append(" AND a.FlowingWaterNumber LIKE @FlowingWaterNumber");
                    page.Append(" AND a.FlowingWaterNumber LIKE @FlowingWaterNumber");
                }

                if (request.PayableManagementType.HasValue)
                {
                    sb.Append(" AND a.PayableManagementType = @PayableManagementType");
                    page.Append(" AND a.PayableManagementType = @PayableManagementType");
                }

                if (!string.IsNullOrEmpty(request.Payer))
                {
                    sb.Append(" AND a.Payer LIKE @Payer");
                    page.Append(" AND a.Payer LIKE @Payer");
                }

                if (request.STime != null && request.ETime != null)
                {
                    sb.Append(" AND a.CreatTime BETWEEN @STime AND @ETime");
                    page.Append(" AND a.CreatTime BETWEEN @STime AND @ETime");
                }

                if (request.State.HasValue)
                {
                    sb.Append(" AND a.State = @State");
                    page.Append(" AND a.State = @State");
                }

                if (request.rid.HasValue)
                {
                    sb.Append(" AND a.rid = @rid");
                    page.Append(" AND a.rid = @rid");
                }

                sb.Append(" ORDER BY a.ReceivablesManagementId DESC LIMIT @PageSize OFFSET @offset");
                var parameters = new
                {
                    FlowingWaterNumber = $"%{request.FlowingWaterNumber}%",
                    PayableManagementName = $"%{request.PayableManagementName}%",
                    request.PayableManagementType,
                    Payer = $"%{request.Payer}%",
                    STime = request.STime,
                    ETime = request.ETime,
                    request.State,
                    request.rid,
                    offset = (request.PageIndex - 1) * request.PageSize,
                    request.PageSize
                };

                var pageData = await db.DapperConnection.QueryAsync<ReceivablesManagementDto>(sb.ToString(), parameters);
                int totalCount = await db.DapperConnection.ExecuteScalarAsync<int>(page.ToString(), parameters);
                int totalPage = (int)Math.Ceiling(totalCount / (double)request.PageSize);

                result.PageDatas = pageData.ToList();
                result.TotalCount = totalCount;
                result.TotalPage = totalPage;
                result.Message = "应付管理显示成功";
                result.Code = APIEnum.Ok;
                return result;

            }
            catch (Exception ex)
            {
                logger.LogError("应收管理显示失败" + ex.Message);
                throw;
            }
        }
    }
}
